//
//  XS_BaseVC.swift
//  Pods
//
//  Created by 韩云智 on 2020/7/15.
//

import UIKit
import RxCocoa
import RxSwift

public var defaultOrientation: UIInterfaceOrientation = .landscapeRight

open class XS_BaseVC: UIViewController {
    //MARK:-RxSwift
    open lazy var disposeBag = DisposeBag()
    
    //MARK:-转屏
    open lazy var orientations: UIInterfaceOrientationMask = .portrait
    open override var shouldAutorotate: Bool { get { return true } }
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask { get { return orientations } }
    open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        get {
            switch orientations {
            case .portrait:
                return .portrait
            case .portraitUpsideDown:
                return .portraitUpsideDown
            case .landscapeLeft:
                defaultOrientation = .landscapeLeft
                return .landscapeLeft
            case .landscapeRight:
                defaultOrientation = .landscapeRight
                return .landscapeRight
            case .landscape:
                switch UIDevice.current.orientation {
                case .landscapeRight:
                    defaultOrientation = .landscapeLeft
                    return .landscapeLeft
                case .landscapeLeft:
                    defaultOrientation = .landscapeRight
                    return .landscapeRight
                default:
                    return defaultOrientation
                }
            default:
                let ori = UIApplication.shared.statusBarOrientation
                if ori == .landscapeLeft || ori == .landscapeRight {
                    defaultOrientation = ori
                }
                return ori
            }
        }
    }
    
    //MARK:-生命周期
    deinit {
        xsDebug { print("deinit: \(type(of: self))") }
        NotificationCenter.default.removeObserver(self)
    }
    // 需要在初始化时,进行的操作
    open func upConfig() {}
    open func upView() {}
    public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        upConfig()
        if #available(iOS 13.0, *) { overrideUserInterfaceStyle = .light }
    }
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    open override func viewDidLoad() {
        super.viewDidLoad()
        xsDebug { print("load: \(type(of: self))") }
        navigationItem.backBarButtonItem = UIBarButtonItem(title: nil, style: .plain, target: nil, action: nil)
        view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        upView()
    }
    //MARK:-导航条
    // 隐藏导航条
    open lazy var shouldNavBarHidden: Bool = false
    open lazy var isStatusBarBlack: Bool = true
    // 自定义透明导航
    open lazy var shouldCustomBarBack: Bool = true
    open lazy var customBar: XS_NavBar = {
        let bar = XS_NavBar()
        let itemTop = UINavigationItem(title: navigationItem.title ?? title ?? "")
        var items = [itemTop]
        if shouldCustomBarBack {
            let itemBack = UINavigationItem(title: "")
            items.insert(itemBack, at: 0)
            bar.delegate = self
        }
        bar.setItems(items, animated: false)
        bar.tintColor = isStatusBarBlack ? #colorLiteral(red: 0.2588235294, green: 0.2588235294, blue: 0.2588235294, alpha: 1) : #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        bar.titleTextAttributes = [
            .font : UIFont.xsFont(name: .semibold, 18),
            .foregroundColor : isStatusBarBlack ? #colorLiteral(red: 0.2588235294, green: 0.2588235294, blue: 0.2588235294, alpha: 1) : #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        ]
        return bar
    }()
    // 自定义透明导航
    open func loadCustomBar() {
        view.addSubview(customBar)
        customBar.snp.makeConstraints { maker in
            maker.top.equalToSuperview().offset(CGFloat.barHeight)
            maker.left.equalTo(8)
            maker.right.equalToSuperview()
            maker.height.equalTo(44)
        }
    }
    open func loadHCustomBar() {
        view.addSubview(customBar)
        customBar.snp.makeConstraints { maker in
            maker.left.equalTo(8)
            maker.right.top.equalToSuperview()
            maker.height.equalTo(44)
        }
    }
    // 状态栏颜色
    open override var preferredStatusBarStyle: UIStatusBarStyle {
        if #available(iOS 13.0, *) {
            return isStatusBarBlack ? .darkContent : .lightContent
        } else {
            return isStatusBarBlack ? .default : .lightContent
        }
    }
    open override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 隐藏/展示导航条的操作
        navigationController?.setNavigationBarHidden(shouldNavBarHidden, animated: animated)
    }
    //MARK:-键盘
    // 键盘弹出修改self.view.frame
    open lazy var shouldChangeViewWithKeyBoard: Bool = false
    // 点击空白处收起键盘
    open lazy var shouldEndEditing: Bool = false
    open override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if shouldChangeViewWithKeyBoard { // 键盘监听
            NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(notification:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
        }
    }
    open override func viewWillDisappear(_ animated: Bool) {
        if shouldChangeViewWithKeyBoard { // 键盘取消监听
            NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
        }
        super.viewWillDisappear(animated)
    }
}

/// keyboard 相关操作
public extension XS_BaseVC {
    open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if shouldEndEditing { // 收起键盘
            view.endEditing(true)
        }
    }
    
    @objc private func keyboardWillChangeFrame(notification: NSNotification) {
        guard let info = notification.userInfo else {
            return
        }
        let duration = info[UIResponder.keyboardAnimationDurationUserInfoKey] as! CGFloat
        let endKeyboardRect = info[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
        
        UIView.animate(withDuration: TimeInterval(duration)) {
            var frame = self.view.frame
            frame.size.height = endKeyboardRect.origin.y - frame.origin.y
            self.view.frame = frame
            self.view.layoutSubviews()
        }
    }
}

/// 导航相关
extension XS_BaseVC: UINavigationBarDelegate {
    // 自定义bar 点击返回操作处理
    open func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
        if let nvc = navigationController {
            if nvc.viewControllers.count > 1 {
                nvc.popViewController(animated: true)
            } else {
                nvc.dismiss(animated: true)
            }
        } else {
            dismiss(animated: true)
        }
        return false
    }
    // 复合页面弹出
    open func xsPresent(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
        if let pvc = presentedViewController {
            pvc.dismiss(animated: false) { [weak self] in
                self?.present(viewControllerToPresent, animated: flag, completion: completion)
            }
        } else {
            present(viewControllerToPresent, animated: flag, completion: completion)
        }
    }
}
